package com.reins.bookstore.serviceimpl;

import com.reins.bookstore.dao.BookDao;
import com.reins.bookstore.dao.OrderDao;
import com.reins.bookstore.entity.Book;
import com.reins.bookstore.entity.Orders;
import com.reins.bookstore.entity.OrderItem;
import com.reins.bookstore.object.*;
import com.reins.bookstore.service.OrderService;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;


@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private BookDao bookDao;

    @Override
    public Orders findOrderById(Integer id){
        return orderDao.findById(id);
    }




    //得到的是Orders表格中的数据
    @Override
    public List<Orders> findOrdersByUserId(Integer userId){
        return orderDao.findAllOrdersByUserId(userId);
    }

    /*
     * 得到的是整个详细的Order数据
     * 如果id == 0,则获取所有订单信息
     */

    @Override
    public List<OrderDTO> findAllOrders(Filter filter){
        List<Orders> temp_orders = new LinkedList<>();
        List<OrderItem> temp_orderItem = new LinkedList<>();
        List<OrderDTO> res = new LinkedList<>();
        if (filter == null)
            temp_orders = orderDao.findAll();
        else if (filter.getUserId() == 0)
            if (filter.getFrontDate() == null)
                temp_orders = orderDao.findAll();
            else
                temp_orders = orderDao.findAll(filter.getFrontDate(),filter.getBackDate());
        else
            if(filter.getFrontDate() == null)
                temp_orders = orderDao.findAllOrdersByUserId(filter.getUserId());
            else
            // 第一步，找到这个用户id下的所有订单id
                temp_orders = orderDao.findAllOrdersByUserId(filter.getUserId(),filter.getFrontDate(),filter.getBackDate());


        // 第二步，根据每个order，找一组orderlist，组装成一个totalorder,加入到res中。
        res = buildOrderDTO(temp_orders);
        return res;
    }

    @Override
    public List<OrderDTO> findAllOrders(){
        List<Orders> temp_orders = new LinkedList<>();
        List<OrderDTO> res = new LinkedList<>();
        temp_orders = orderDao.findAll();

        // 第二步，根据每个order，找一组orderlist，组装成一个totalorder,加入到res中。
        res = buildOrderDTO(temp_orders);
        return res;
    }

    @Override
    public List<OrderDTO> findGlobalOrders(){
        List<Orders> temp_orders = new LinkedList<>();
        List<OrderItem> temp_orderItem = new LinkedList<>();
        List<OrderDTO> res = new LinkedList<>();
        // 第一步，找到所有图书
        temp_orders = orderDao.findAll();

        // 第二步，根据每个order，找一组orderlist，组装成一个totalorder,加入到res中。

        int userId;
        res = buildOrderDTO(temp_orders);
        return res;
    }
    private List<OrderDTO> buildOrderDTO(List<Orders> temp_orders){
        List<OrderDTO> res = new ArrayList<>();
        int userId = 0;
        for (Orders one_orders : temp_orders)
        {
            userId = one_orders.getUserAuth().getUserId();
            // 根据order的id找所有的list
            int orderId = one_orders.getOrderId();
            BigDecimal totalorderCost = new BigDecimal(0);
            List<OrderItem> orderItem_add = new LinkedList<>();
            List<BasketlineDTO> totalorderBooks = new LinkedList<>();
            List<Integer> totalorderNums = new LinkedList<>();

            orderItem_add = orderDao.findAllOrderlistsByOrderId(orderId);
            int len_list = orderItem_add.size();

            for(OrderItem one_order_list : orderItem_add)
            {
                Book add_book = one_order_list.getBook();
                BookDTO add_book_dto = new BookDTO(add_book);
                BasketlineDTO add_buylist_dto = new BasketlineDTO(add_book,one_order_list.getBookNum());
                totalorderBooks.add(add_buylist_dto);
                totalorderCost = totalorderCost.add(one_order_list.getListCost());
            }

            OrderDTO add_orderDTO = new OrderDTO(one_orders,totalorderCost,totalorderBooks);
            res.add(add_orderDTO);
        }
        return res;
    }

    /*
     * 找到规定时间内最热的书，同时考虑分页情况
     * TODO:未完成
     */
    @Override
    public List<HotListDTO> getHotBooks(Filter filter){
        // 第一步找出所有orders
        List<Orders> get_all_orderses = orderDao.findAll(filter.getFrontDate(),filter.getBackDate());   //找出规定时间内的所有订单

        List<HotListDTO> get = new ArrayList<>();   // 填充get返回值

        for (Orders one_order : get_all_orderses){

        }

        return null;
    }

    @Override
    public Orders saveOrder(Orders add){
        return orderDao.save(add);
    }

    @Override
    public Orders editOrder(Orders edit){return orderDao.save(edit);}

    @Override
    public boolean deleteOrderById(int id){
        boolean result = true;
        try{
            orderDao.deleteOrderById(id);
            orderDao.deleteOrderItemsByOrderId(id);
        }
        catch (Exception ex){
            result = false;
        }
        return result;
    }

    @Override
    public boolean deleteOrderByUserId(Integer userId){
        List<Orders> del_list = findOrdersByUserId(userId);  // 先找到所有的相关order
        for (Orders del: del_list)
        {
            orderDao.deleteOrderById(del.getOrderId());

        }
        return false;
    }

    @Override
    public BigDecimal buyOneBook(OneBookOrder params){
        Integer res_bookId = params.getBookId();
        Integer res_userId = params.getUserId();
        Integer res_num = params.getBookNum();
        BigDecimal res_price = params.getPrice();
        BigDecimal mid_num = new BigDecimal(res_num);
        BigDecimal res_total = res_price.multiply(mid_num);
        Date test = new Date();
        TimeZone time = TimeZone.getTimeZone("GMT+8");
        TimeZone.setDefault(time);

        Date add_date = new Date();
        // 在Order表中写入
        Orders add_orders = new Orders(null,res_userId,add_date);

        add_orders = orderDao.saveAndFlush(add_orders);

        Integer res_orderId = add_orders.getOrderId();
        // 在OrderList表中写入
        OrderItem add_list = new OrderItem(null,res_bookId,res_num,res_orderId,res_total);
        orderDao.savelist(add_list);


        return res_total;
    }

    @Override
    public BigDecimal buyThreeBooks(ThreeBooksOrder params){
        Integer res_userId = params.getUserId();
        List<OneBookList> oneBookLists = params.getOnebooklist();

        BigDecimal res_cost = new BigDecimal(0);

        Integer bookId;
        Integer bookNum;
        BigDecimal listCost;
        BigDecimal totalCost = new BigDecimal(0);

        TimeZone time = TimeZone.getTimeZone("ETC/GMT-8");
        TimeZone.setDefault(time);

        Date add_time = new Date();
        Orders add_orders = new Orders(null,res_userId,add_time);
        add_orders = orderDao.saveAndFlush(add_orders);
        Integer res_orderId = add_orders.getOrderId();

        for (OneBookList oneBookList : oneBookLists){
            // 获取值
            bookId = oneBookList.getBookId();
            bookNum = oneBookList.getBookNum();
            BigDecimal mid_num = new BigDecimal(bookNum);
            listCost = oneBookList.getBookPrice();
            listCost = listCost.multiply(mid_num);
            OrderItem add_orderItem = new OrderItem(null,bookId,bookNum,res_orderId,listCost);
            orderDao.savelist(add_orderItem);
            totalCost = totalCost.add(listCost);
        }

        return totalCost;
    }

}
